from datetime import datetime, timedelta
from bodhi.utils.http import patch_vary_headers

from .base import Session

class SessionFilter:
    order = 80

    def __init__(self, session_factory, cookie_name='sessionid', save_when_accessed=False, expire_at_browser_close=False, cookie_age=86400*7, cookie_domain=None, cookie_path='/', cookie_secure=False):
        self.session_factory = session_factory
        self.cookie_name = cookie_name
        self.save_when_accessed = save_when_accessed
        self.expire_at_browser_close = expire_at_browser_close
        self.cookie_age = cookie_age
        self.cookie_domain = cookie_domain
        self.cookie_path = cookie_path
        self.cookie_secure = cookie_secure

    def __call__(self, view, next):
        """
        If view.session was dirty, or if the configuration is to save the
        session when session is accessed, save the changes and set
        a session cookie.
        """
        session_id = view.request.get_cookie(self.cookie_name)
        view.session = session = self.session_factory(session_id=session_id, session_age=self.cookie_age)

        response = next()

        accessed = session.accessed
        dirty = session.dirty

        if accessed:
            patch_vary_headers(response, ('Cookie',))
        if dirty:
            session.save()
        elif self.save_when_accessed and accessed:
            session.renew()
        if dirty or (self.save_when_accessed and accessed) or session.is_new:
            max_age = None if self.expire_at_browser_close else self.cookie_age 
            response.set_cookie(self.cookie_name,
                    session.session_id, 
                    max_age=max_age,
                    domain=self.cookie_domain,
                    path=self.cookie_path,
                    secure=self.cookie_secure,
                    httponly=True)
        return response

